/*
大结算界面(该房间游戏结束)，整个界面的处理逻辑
*/
var confige = require("confige");
var gameData = require("gameData");
cc.Class({
    extends: cc.Component,

    properties: {
        headOri:{
            default:null,
            type:cc.SpriteFrame
        },
        isInit:false,
        shareTitle:"",
        shareDes:"",
    },

    // use this for initialization
    onLoad: function () {
        
    }, 
    
    onInit:function(){
        this.infoListNode = this.node.getChildByName("infoList");
        this.infoList = {};
        for(var i=0;i<9;i++)
            this.infoList[i] = this.infoListNode.getChildByName("infoNode"+i);
        
        this.overDataCount = 0;
        this.shareBtn = this.node.getChildByName("btn_other").getComponent("cc.Button");
        confige.curOverLayer = this;
        if(cc.sys.platform == cc.sys.MOBILE_BROWSER)
        {
            this.node.height = 790;
            this.bgNode = this.node.getChildByName("gameOverBg");
            this.bgNode.height = 790;
            this.h5ShareNode = this.node.getChildByName("h5Share");
            this.h5ShareNode.opacity = 0;
            this.h5ShareNode.active = false;
            // this.shareBtnNode = this.node.getChildByName("btn_other");
            // this.shareBtnNode.active = false;
        }

        this.curOverData = {};
        this.selectInfo = this.node.getChildByName("selectInfo");
        this.selectInfoS = this.selectInfo.getComponent("overItem");
        this.selectInfoS.onInit();

        this.isInit = true;
        var testDate = new Date();
        console.log("房间信息")
        console.log(confige.roomData)
        this.itemNode = this.node.getChildByName("itemNode");
        this.node.getChildByName("roomidtext").getComponent(cc.Label).string =  confige.roomData.roomId;
        this.node.getChildByName("fentext").getComponent(cc.Label).string = confige.roomData.basic;
        this.node.getChildByName("jushu").getComponent(cc.Label).string = confige.roomData.maxGameNumber + "局";
        this.node.getChildByName("time").getComponent(cc.Label).string = testDate.getFullYear() + "/" + (testDate.getMonth() + 1) + "/" + testDate.getDate() + "  " + testDate.getHours() + ":" + testDate.getMinutes() + ":" + testDate.getSeconds();
        this.roomMode =  this.node.getChildByName("roominfo").getComponent(cc.Label);
        if(confige.roomData.roomType == "sanKung")
        {
            this.roomMode.string = "三公";
            if(confige.roomData.bankerMode == 6)
                this.roomMode.string = "三公(九点当庄)";
            if(confige.roomData.bankerMode == 7)
                this.roomMode.string = "三公(大吃小)";
            if(confige.roomData.bankerMode == 3)
                this.roomMode.string = "三公(轮庄)";
            if(confige.roomData.bankerMode == 8)
                this.roomMode.string = "三公(加倍抢庄)";
            if(confige.roomData.bankerMode == 2)
                this.roomMode.string = "三公(房主当庄)";
        }
        if(confige.roomData.roomType == "zhajinhua")
        {
            this.roomMode.string = "炸金花";
        }
        if(confige.roomData.roomType == "PaiGow")
        {
            this.roomMode.string = "雀九";
            if(confige.roomData.bankerMode == 6)
                this.roomMode.string = "雀九(九点当庄)";
            if(confige.roomData.bankerMode == 7)
                this.roomMode.string = "雀九(大吃小)";
            if(confige.roomData.bankerMode == 3)
                this.roomMode.string = "雀九(轮庄)";
            if(confige.roomData.bankerMode == 8)
                this.roomMode.string = "雀九(加倍抢庄)";
        }
        if(confige.roomData.roomType == "PaiGowBalcony")
            this.roomMode.string = "房主坐庄";
    
    },

    addOneOverData:function(playerData,master,cardHistory){
        console.log(playerData);
        var curInfoNode = this.infoList[playerData.chair].getComponent("overItem");
        curInfoNode.onInit();
        this.infoList[playerData.chair].active = true;

        curInfoNode.setName(playerData.playerInfo.nickname);
        curInfoNode.setID(playerData.uid);
        curInfoNode.setBankerCount(playerData.bankerCount);
        curInfoNode.setHead(playerData.playerInfo.head);
        curInfoNode.setScore(playerData.score);
        // if(master == true)
        //     curInfoNode.showMaster();
    },
    
    showOverWithData:function(overData){
        this.lastSelectIndex = confige.meChair;
        console.log("overData@@@@@====");
        console.log(overData);
        this.curOverData = overData;

        this.maxScore = 0;
        this.maxChair = -1;
        for(var i in overData.player)
        {
            // this.newOverDataList[i] = {};
            var newPlayerData = overData.player[i];
            var newCardHistory = overData.cardHistory[i];
            if(newPlayerData.isActive == true)
            {
                var master = false;
                if(i === 0)
                    master = true;

                this.addOneOverData(newPlayerData,master,newCardHistory);

                if(newPlayerData.score > this.maxScore)
                {
                    this.maxScore = newPlayerData.score;
                    this.maxChair = newPlayerData.chair;
                }
            }
        }
        this.updateSelectData(-1,confige.meChair);
        for(var i in overData.player)
        {
            var newPlayerData = overData.player[i];
            if(newPlayerData.isActive == true && newPlayerData.chair != this.maxChair)
            {
                this.shareDes += "【"+newPlayerData.playerInfo.nickname+"】:"+newPlayerData.score+";";
            }
        }
        
        if(this.maxChair != -1)
        {
            // this.newOverDataList[this.maxChair].winIco.active = true;
            this.shareTitle = "★大赢家【"+overData.player[this.maxChair].playerInfo.nickname+"】 : "+overData.player[this.maxChair].score;
        }

        if(cc.sys.platform == cc.sys.MOBILE_BROWSER){
            var self = this;
            console.log("H5分享给好友");
            var curShareURL = confige.h5ShareUrlNew.replace('ROOMNUM', '0');
            if(confige.h5InviteCode != "0")
            {
                curShareURL += "&invite_code=" + confige.h5InviteCode;
            }
            wx.onMenuShareAppMessage({
                title: self.shareTitle,
                desc: self.shareDes,
                link: curShareURL,
                imgUrl: confige.h5ShareIco,
                trigger: function(res) {},
                success: function(res) {},
                cancel: function(res) {},
                fail: function(res) {}
            });
            console.log("H5分享到朋友圈2222222");
            wx.onMenuShareTimeline({
                title: self.shareTitle,
                desc: self.shareDes,
                link: curShareURL,
                imgUrl: confige.h5ShareIco,
                trigger: function(res) {},
                success: function(res) {},
                cancel: function(res) {},
                fail: function(res) {}
            });
        }
    },

    onBtnStartGameClick:function(){
        window.DKTools.audioEG.playEffect("tips_btnClick");
        confige.curOverLayer = -1;
        // cc.loader.onProgress = function(completedCount, totalCount, item) {
        //     // cc.log('step 1----------');
        //     var progress = (completedCount / totalCount).toFixed(2);
        //     // cc.log(progress + '%' + completedCount + "///" + totalCount);
        //     var numString = "" + completedCount + "/" + totalCount;
        //     if(totalCount > 10){
        //         confige.loadNode.showNode();
        //         confige.loadNode.setProgress(progress,numString);
        //     }
        // };
        cc.director.loadScene('HallScene');
        if(confige.curGameScene.yuyinTimeOut != -1)
            clearTimeout(confige.curGameScene.yuyinTimeOut);
        confige.curGameScene.destroy();
        confige.resetGameData();
        if(confige.curUsePlatform == 1)
        {
            window.GVoice.quitRoom(window.GVoice.GVoiceRoomID);
            window.GVoice.closeListen();
        }
    },
    
    onBtnOtherClick:function(){
        window.DKTools.audioEG.playEffect("tips_btnClick");
        console.log("点击分享111111111111111");
        if(cc.sys.platform == cc.sys.MOBILE_BROWSER){
            var self = this;
            console.log("H5分享给好友");
            var curShareURL = confige.h5ShareUrlNew.replace('ROOMNUM', '0');
            if(confige.h5InviteCode != "0")
            {
                curShareURL += "&invite_code=" + confige.h5InviteCode;
            }
            wx.onMenuShareAppMessage({
                title: self.shareTitle,
                desc: self.shareDes,
                link: curShareURL,
                imgUrl: confige.h5ShareIco,
                trigger: function(res) {},
                success: function(res) {},
                cancel: function(res) {},
                fail: function(res) {}
            });
            console.log("H5分享到朋友圈2222222");
            wx.onMenuShareTimeline({
                title: self.shareTitle,
                desc: self.shareDes,
                link: curShareURL,
                imgUrl: confige.h5ShareIco,
                trigger: function(res) {},
                success: function(res) {},
                cancel: function(res) {},
                fail: function(res) {}
            });

            this.h5ShareNode.active = true;
            this.h5ShareNode.stopAllActions();
            this.h5ShareNode.opacity = 255;
            var deactiveCall = cc.callFunc(function () {
                this.h5ShareNode.active = false;
            },this);
            this.h5ShareNode.runAction(cc.sequence(cc.delayTime(2),cc.fadeOut(1),deactiveCall));
        }
        if (!cc.sys.isNative) return;
        let dirpath = jsb.fileUtils.getWritablePath() + 'ScreenShoot/';
        if (!jsb.fileUtils.isDirectoryExist(dirpath)) {
            jsb.fileUtils.createDirectory(dirpath);
        }
        let name = 'ScreenShoot-' + (new Date()).valueOf() + '.png';
        let filepath = dirpath + name;
        let size = cc.winSize;
        let rt = cc.RenderTexture.create(size.width, size.height,cc.Texture2D.PIXEL_FORMAT_RGBA8888, gl.DEPTH24_STENCIL8_OES);
        cc.director.getScene()._sgNode.addChild(rt);
        rt.setVisible(false);
        rt.begin();
        cc.director.getScene()._sgNode.visit();
        rt.end();
        rt.saveToFile('ScreenShoot/' + name, cc.ImageFormat.PNG, true, function() {
            cc.log('save succ');
            rt.removeFromParent();
            if(confige.curUsePlatform == 1)
            {
                jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "JAVALog", "(Ljava/lang/String;)V", "filepath222==="+filepath);
                jsb.reflection.callStaticMethod("org/cocos2dx/javascript/JSCallJAVA", "WXShareScreenPath", "(Ljava/lang/String;)V", filepath);
            }else if(confige.curUsePlatform == 2){
                jsb.reflection.callStaticMethod("JSCallOC","WXShareScreenWithPath:",filepath);
            }
        });

        this.shareBtn.interactable = false;
    },

    openShare:function(){
        this.shareBtn.interactable = true;
    },

    showLayer:function(){
        if(this.isInit == false)
            this.onInit();
        this.node.active = true;
    },

    hideLayer:function(){
        this.node.active = false;
        this.selectHead = -1;
    },

    hideH5ShareNode:function(){
        this.h5ShareNode.stopAllActions();
        this.h5ShareNode.opacity = 0;
        this.h5ShareNode.active = false;
    },

    updateSelectData:function(event, customEventData){
        var index = parseInt(customEventData);
        // this.infoList[this.lastSelectIndex].node.getChildByName("bgSelect").active = false;
        this.lastSelectIndex = index;
        // this.infoList[this.lastSelectIndex].node.getChildByName("bgSelect").active = true;
        var playerData = this.curOverData.player[index];
        var cardHistory = this.curOverData.cardHistory[index];
        console.log(playerData);
        console.log(cardHistory);
        console.log(this.curOverData);

        var typeCount1=0,typeCount2=0,typeCount3=0,typeCount4=0,typeCount5=0,typeCount6=0,typeCount7=0,typeCount8=0,typeCount9=0,typeCount10=0;
        for(var i in cardHistory)
        {
            var newType = cardHistory[i].type;                    
            if(newType == 9)
                typeCount1++;
            else if(newType == 8)
                typeCount2++;
            else if(newType >10)
                typeCount3++;
        }
        this.selectInfo.getChildByName("paiGowNode").getChildByName("node0").getChildByName("time").getComponent("cc.Label").string = typeCount1;
        this.selectInfo.getChildByName("paiGowNode").getChildByName("node1").getChildByName("time").getComponent("cc.Label").string = typeCount2;
        this.selectInfo.getChildByName("paiGowNode").getChildByName("node2").getChildByName("time").getComponent("cc.Label").string = typeCount3;
        
        this.selectInfoS.setName(playerData.playerInfo.nickname);
        this.selectInfoS.setID(playerData.uid);
        this.selectInfoS.setHead(playerData.playerInfo.head);
        this.selectInfoS.setScore(playerData.score);
    },

    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});
